package com.acraftsman.mr_camera;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.annotation.NonNull;

import com.sosocam.ipcam.IPCam;
import com.sosocam.ipcammgr.IPCamMgr;
import com.sosocam.rcipcam.DISCOVERED_CAMERA_INFO;

import java.util.LinkedHashMap;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** MrCameraPlugin */
public class MrCameraPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Context context;
  private Activity activity;
  private static final int REQUEST_IMR_PHOTO = 1;
  private Result pendingResult;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "com.acraftsman/mr_camera");
    channel.setMethodCallHandler(this);
    context = flutterPluginBinding.getApplicationContext();
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("startScanService")) {
      startScanService();
      result.success("SUCCESS");
    } else if (call.method.equals("stopScanService")) {
      stopScanService();
      result.success("SUCCESS");
    } else if (call.method.equals("isScanServiceRunning")) {
      result.success(isScanServiceRunning());
    } else if (call.method.equals("startClientActivity")) {
      startClientActivity(call.argument("userDetail"),call.argument("snapshotFilePath"));
      pendingResult = result;
    } else if (call.method.equals("getIpCamCount")) {
      Integer camCount = getIpCamCount();
      result.success(camCount);
    } else if (call.method.equals("rediscoverCameras")) {
      rediscoverCameras();
      result.success("SUCCESS");
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  @Override
  public void onAttachedToActivity(ActivityPluginBinding binding) {
    activity = binding.getActivity();
    binding.addActivityResultListener((requestCode, resultCode, data) -> {
      this.onActivityResult(requestCode, resultCode, data);
      return false;
    });
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {
    activity = null;
  }

  @Override
  public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
    activity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivity() {
    activity = null;
  }

  public void startScanService() {
    Intent intent = new Intent(context, ScanService.class);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      //android8.0以上通过startForegroundService启动service
      context.startForegroundService(intent);
    } else {
      context.startService(intent);
    }
  }

  public void stopScanService() {
    Intent intent = new Intent(context, ScanService.class);
    context.stopService(intent);
  }

  public boolean isScanServiceRunning() {
    return ScanService.isServiceRunning();
  }

  private void startClientActivity(String userDetailStr, String snapshotFilePath) {
    //跳转页面
    Intent intent = new Intent(activity, ClientActivity.class);
    intent.putExtra("userDetail", userDetailStr);
    intent.putExtra("snapshotFilePath", snapshotFilePath);
    activity.startActivityForResult(intent, REQUEST_IMR_PHOTO);
  }

  private Integer getIpCamCount() {
    LinkedHashMap<String, DISCOVERED_CAMERA_INFO> disCamList = IPCamMgr.get_discovered_cameras_list();
    if(disCamList != null && !disCamList.isEmpty()) {
      return disCamList.size();
    }
    return 0;
  }

  public void rediscoverCameras() {
    IPCamMgr.rediscover_cameras();
  }

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMR_PHOTO) {
      if (pendingResult != null) {
        if (data != null) {
          pendingResult.success(data.getStringExtra("result"));
        } else {
          pendingResult.success("error");
        }
      }
    }
  }
}
